package com.alibaba.basic.controller;


import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传：1 - Post
 * 下载：不需要
 * 删除：1 - Delete
 * 修改： = 删除 + 上传
 */
@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {

    /**
     * 上传接口
     * @param file
     * @return
     */
    @PostMapping
    //el-upload提供的文件上传框默认的name="file"
    public AjaxResult upload(@RequestPart MultipartFile file){
        try {
            String originalFilenam = file.getOriginalFilename(); // 404.png
            //获取文件后缀
            String extName = originalFilenam.substring(originalFilenam.lastIndexOf(".")+1);
            ////  /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String filename = FastDfsUtil.upload(file.getBytes(), extName);
            //将上传之后的名字响应给 前端
            return AjaxResult.me().setResultObj(filename);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 删除接口
     * @param path
     * @return
     */
    @DeleteMapping  //http://localhost:8080/department/1
    //http://localhost:8080/department?path=/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
    //到时候前端传： /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
    // group1    M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
    public AjaxResult del(@RequestParam String path){
        try {
            String pathTem = path.substring(1);  //    group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String group = pathTem.substring(0,pathTem.indexOf("/")); //  group1
            String filePath =  pathTem.substring(pathTem.indexOf("/")+1);// M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg

            FastDfsUtil.delete(group,filePath);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }


}
